package com.aftersale.demo.service.impl;

import com.aftersale.demo.entity.LoginUser;
import com.aftersale.demo.entity.User;
import com.aftersale.demo.mapper.PermissionMapper;
import com.aftersale.demo.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
*@Author  空
*@Date    2023/10/23 20:20
*@Desc    UserDetails接口实现类，更改用户信息读取位置为数据库
*/
@Service
public class UserDetailsServiceImpl extends ServiceImpl<UserMapper, User> implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user =userMapper.selectOne(queryWrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名不存在");
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> permissionList =permissionMapper.selectPermissionsByUserId(user.getId());
        //将用户信息及权限封装成UserDetails对象返回，此处LoginUser为UserDtails实现类
        return new LoginUser(user,permissionList);


    }


}
